/*
 * Copyright (C) 2005 - 2030 YGSoft.Inc All Rights Reserved.
 * YGSoft.Inc PROPRIETARY/CONFIDENTIAL.Use is subject to license terms.
 */
package com.example.demo.autoconfig;

import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 自定义服务自动配置类.
 * 用于自动配置MyService Bean，根据条件判断是否启用自动配置.
 * 
 * @author dingdayong
 */
@Configuration
@ConditionalOnClass(MyService.class) // 存在MyService这个类才装配当前类
@ConditionalOnProperty(name = "myservice.enabled", havingValue = "true", matchIfMissing = false) // 配置文件存在这个myservice.enabled=true才启动，允许不存在该配置
@EnableConfigurationProperties(MyServiceProperties.class)
public class MyServiceAutoConfiguration {
	
	/**
	 * 创建MyService Bean.
	 * 当容器中不存在MyService实例时，根据配置属性创建新的MyService实例.
	 * 
	 * @param serviceProperties 服务配置属性
	 * @return MyService实例
	 */
	@Bean
	@ConditionalOnMissingBean(MyService.class) // 没有MyService这个类才进行装配
	public MyService myService(MyServiceProperties serviceProperties) {
		// 
		System.out.println("骚年，你配置的IP为：" + serviceProperties.getHost() + "，端口为：" + serviceProperties.getPort());
		
		// 一开始就执行的代码
		return new MyService(serviceProperties.getHost(), serviceProperties.getPort());
	}
}
